package com.isoft.illustrationsdraw.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.isoft.illustrationsdraw.Constants;
import com.isoft.illustrationsdraw.service.FileService;

@Service
public class FileServiceImpl implements FileService {


    public static final String ILLUSTRATIONS_DIR = "/home/server/pictures/illustrations/{illustrationId}/{collectionIndex}";
    public static final String PROFILEIMG_DIR = "/home/server/pictures/profileimg/{userId}";
    public static final String PRODUCTIMG_DIR = "/home/server/pictures/productimg/{productId}/{productIndex}";



    @Override
    public File createDirectory(String targetDir) throws IOException, IllegalArgumentException {
        if (targetDir == null || targetDir.trim().isEmpty()) {
            throw new IllegalArgumentException(Constants.Error.INVALID_DIR);
        }
    
        File dir = new File(targetDir);
        if (dir.exists()) {
            cleanDirectory(dir);
        }
        boolean created = dir.mkdirs();
        if (!created) {
            throw new IOException(Constants.Error.FAILED_CREATE_DIR + targetDir);
        }

        // if (!dir.exists()) {
        //     boolean created = dir.mkdirs();
        //     if (!created) {
        //         throw new IOException(Constants.Error.FAILED_CREATE_DIR + targetDir);
        //     }
        // }
    
        return dir;
    }

    @Override
    public void cleanDirectory(File dir) throws IOException {
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException("The provided directory is invalid: " + dir);
        }
    
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 递归清理子文件夹
                    cleanDirectory(file);
                }
                // 删除文件或空文件夹，失败时抛出异常
                if (!file.delete()) {
                    throw new IOException("Failed to delete file or directory: " + file.getAbsolutePath());
                }
            }
        }
    
        // 删除当前目录，失败时抛出异常
        if (!dir.delete()) {
            throw new IOException("Failed to delete directory: " + dir.getAbsolutePath());
        }
    }
    

    @Override
    public List<String> listFilesInDirectory(File dir) throws IOException, IllegalArgumentException {
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException(Constants.Error.INVALID_DIR);
        }

        File[] files = dir.listFiles();
        if (files == null) {
            throw new IOException(Constants.Error.FAILED_READ_DIR + dir.getAbsolutePath());
        }

        List<String> filePaths = new ArrayList<>();
        for (File file : files) {
            if (file.isDirectory()) {
                throw new IllegalArgumentException(Constants.Error.UNEXPECTED_SUB_DIR + file.getName());
            }
            filePaths.add(file.getAbsolutePath());
        }

        return filePaths;
    }

    @Override
    public List<File> saveFiles(File targetDir, List<MultipartFile> files) throws IOException, IllegalArgumentException {
        if (files == null || files.isEmpty()) {
            throw new IllegalArgumentException(Constants.Error.NO_FILE);
        }
    
        if (targetDir == null || !targetDir.exists() || !targetDir.isDirectory()) {
            throw new IllegalArgumentException(Constants.Error.DIR_NOT_EXIST);
        }
    
        List<File> savedFiles = new ArrayList<>(); // 用于记录已保存的文件
        try {
            int index = 0;
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    throw new IllegalArgumentException(Constants.Error.INVALID_FILE);
                }
    
                // 提取文件扩展名，如果没有扩展名，使用默认值 ".bin"
                String originalFilename = file.getOriginalFilename();
                String extension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                } else {
                    extension = "bin"; // 默认扩展名
                }
    
                // 保存文件，文件名为索引加扩展名
                String filePath = targetDir.getAbsolutePath() + File.separator + index + "." + extension;
                File savedFile = new File(filePath);
                file.transferTo(savedFile);
    
                // 记录已保存的文件
                savedFiles.add(savedFile);
    
                // 索引递增
                index++;
            }
        } catch (Exception e) {
            // 如果出错，删除已保存的文件
            for (File savedFile : savedFiles) {
                if (savedFile.exists()) {
                    savedFile.delete();
                }
            }
    
            // 调用 cleanDirectory 方法清理文件夹
            cleanDirectory(targetDir);
    
            // 抛出异常
            throw new IOException(Constants.Error.FILE_UPLOAD_FAILED + e.getMessage(), e);
        }
    
        return savedFiles; // 返回已保存的文件列表
    }

    @Override
    public File getFileByPath(String path) {
        if (path != null && !path.isEmpty()) {
            File file = new File(path);
            if (file.exists()) {
                return file;
            }
        }
        return null; // 或者抛出异常
    }

    

    // @Override
    // public Resource getFileByPath(String path) {
    //     if (path != null) {
    //         File file = new File(path);
    //         if (file.exists()) {
    //             return new FileSystemResource(file);
    //         }
    //     }

    //     // 返回 null 或抛出异常，表示文件不存在
    //     return null;
    // }

    @Override
    public List<File> saveFilesForChat(File targetDir, List<MultipartFile> files) throws IOException, IllegalArgumentException {
        if (files == null || files.isEmpty()) {
            throw new IllegalArgumentException(Constants.Error.NO_FILE);
        }
    
        if (targetDir == null || !targetDir.exists() || !targetDir.isDirectory()) {
            throw new IllegalArgumentException(Constants.Error.DIR_NOT_EXIST);
        }
    
        List<File> savedFiles = new ArrayList<>(); // 用于记录已保存的文件
        try {
            // 获取文件夹中现有文件的最大数字命名
            int maxIndex = 0;
            File[] existingFiles = targetDir.listFiles((dir, name) -> name.matches("\\d+\\..*"));
            if (existingFiles != null) {
                for (File file : existingFiles) {
                    String fileName = file.getName();
                    int dotIndex = fileName.lastIndexOf('.');
                    if (dotIndex > 0) {
                        String baseName = fileName.substring(0, dotIndex);
                        if (baseName.matches("\\d+")) { // 仅匹配完全由数字组成的文件名
                            try {
                                int currentIndex = Integer.parseInt(baseName);
                                maxIndex = Math.max(maxIndex, currentIndex);
                            } catch (NumberFormatException ignored) {
                                // 忽略解析错误
                            }
                        }
                    }
                }
            }
    
            int index = maxIndex + 1; // 从最大索引的下一个数字开始
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    throw new IllegalArgumentException(Constants.Error.INVALID_FILE);
                }
    
                // 提取文件扩展名，如果没有扩展名，使用默认值 ".bin"
                String originalFilename = file.getOriginalFilename();
                String extension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    extension = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
                } else {
                    extension = "bin"; // 默认扩展名
                }
    
                // 保存文件，文件名为数字索引加扩展名
                String filePath = targetDir.getAbsolutePath() + File.separator + index + "." + extension;
                File savedFile = new File(filePath);
                file.transferTo(savedFile);
    
                // 记录已保存的文件
                savedFiles.add(savedFile);
    
                // 索引递增
                index++;
            }
        } catch (Exception e) {
            // 如果出错，删除已保存的文件
            for (File savedFile : savedFiles) {
                if (savedFile.exists()) {
                    savedFile.delete();
                }
            }
    
            // 调用 cleanDirectory 方法清理文件夹
            cleanDirectory(targetDir);
    
            // 抛出异常
            throw new IOException(Constants.Error.FILE_UPLOAD_FAILED + e.getMessage(), e);
        }
    
        return savedFiles; // 返回已保存的文件列表
    }

    @Override
    public String convertToOnlinePath(String localPath) throws IllegalArgumentException {
        // 基本本地路径（与你 addResourceLocations 配置一致）
        String baseLocalPath = "/home/server/pictures/";

        // 检查本地路径是否以 baseLocalPath 开头
        if (!localPath.startsWith(baseLocalPath)) {
            throw new IllegalArgumentException("Local path is not within the configured base directory.");
        }

        // 去除本地路径的基础路径部分，得到相对路径
        String relativePath = localPath.substring(baseLocalPath.length());

        // 拼接在线路径
        // BASE: http://10.0.0.1:8080/pictures
        return Constants.File.BASE_URL + relativePath.replace("\\", "/"); // 确保路径分隔符是正斜杠
    }
}
